import { MailerService } from '@nestjs-modules/mailer';
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ResponseMsgKey } from '../../../common/constants/api-response.constant';

@Injectable()
export class EmailService {
  private readonly title: string;
  private readonly myEmail: string;
  private readonly logger = new Logger(EmailService.name);

  constructor(
    private readonly mailerService: MailerService,
    private readonly configService: ConfigService,
  ) {
    this.title = this.configService.get<string>('TITLE');
    this.myEmail = this.configService.get<string>('EMAIL_USER');
  }

  /**
   * 发送邮件
   * @param addressee 收件邮箱
   * @param context 邮件内容
   * @param title 标题
   * @returns
   */
  async send(addressee: string, context: any, title = this.title) {
    try {
      return await this.mailerService.sendMail({
        from: `${this.title} ${this.myEmail}`,
        to: addressee,
        subject: title,
        text: context,
      });
    } catch (error) {
      this.logger.error(error);
      throw new Error(ResponseMsgKey.TOO_MANY_REQUESTS);
    }
  }
}
